package sun.jvmstat.monitor;

import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Set;

/**
 * 本例所使用的类库是${JAVA_HOME}/lib/tools.jar
 * @author Ackles
 */
public class MonitorDemo {

	public static void main(String[] args) {
		printVms(args);
	}
	
	public static void printVms(String[] args) {
		try {
			// 获取监控主机
			MonitoredHost monitoredHost = MonitoredHost.getMonitoredHost("localhost");
			// 获取所有活动的java虚拟机程序的进程id
			Set<Integer> activeVms = new HashSet<>(monitoredHost.activeVms());
			System.out.println(activeVms);
			for (Integer pid : activeVms) {
				// 获取java虚拟机进程启动类名
				MonitoredVm vm = monitoredHost.getMonitoredVm(new VmIdentifier(String.valueOf(pid)));
				String mainClass = MonitoredVmUtil.mainClass(vm, true);
				System.out.println(String.format("pid:%d, jvmArgs:%s, MainClass:%s, mainArgs:%s", pid, MonitoredVmUtil.jvmArgs(vm), mainClass, MonitoredVmUtil.mainArgs(vm)));
			}
		} catch (MonitorException | URISyntaxException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据java程序启动类获取对应的程序进程id,
	 * 这里有个问题,相同的程序可以启动多个,因此存在获得多个pid的情况
	 * @param mainClassName
	 * @return
	 */
	public static int getPid(String mainClassName) {
		try {
			MonitoredHost monitoredHost = MonitoredHost.getMonitoredHost("localhost");
			Set<Integer> pids = new HashSet<>(monitoredHost.activeVms());
			for (Integer pid : pids) {
				MonitoredVm vm = monitoredHost.getMonitoredVm(new VmIdentifier(String.valueOf(pid)));
				String mainClass = MonitoredVmUtil.mainClass(vm, true);
				if (mainClass.equalsIgnoreCase(mainClassName)) {
					return pid.intValue();
				}
			}
		} catch (MonitorException | URISyntaxException e) {
			e.printStackTrace();
		}
		return -1;
	}
}
